﻿using Geek.Server.Core.Net.Http;
using Geek.Server.Core.Serialize;
using RestSharp;

namespace Geek.Server.Core.Utils
{
    public static class WebCenterUtils
    {
        private static readonly Lazy<RestClient> Client = new(CreateClient);

        private static RestClient CreateClient()
        {
            return new RestClient(new RestClientOptions(Settings.CenterUrl));
        }

        public static Task<HttpResponse> SendAsync(HttpRequest request, CancellationToken token = default)
        {
            return SendAsync<HttpResponse>(request, token);
        }
        
        public static async Task<T> SendAsync<T>(HttpRequest request, CancellationToken token = default) where T : HttpResponse, new()
        {
            var restRequest = new RestRequest()
                .AddQueryParameter("api", request.Route)
                .AddStringBody(request.ToJsonStr(), DataFormat.Json);

            var resp = await Client.Value.PostAsync(restRequest, token);
            if (resp.Content != null)
                return resp.Content.FromJsonStr<T>();

            return new T
            {
                ErrorCode = 1000002
            };
        }
    }
}